package com.jason.SnippetManager.ui;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

import javax.swing.JList;
import javax.swing.JEditorPane;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.SQLException;

import com.jason.SnippetManager.SQLiteCalls.*;
import javax.swing.JButton;
import com.jgoodies.forms.layout.FormLayout;
import com.jgoodies.forms.layout.ColumnSpec;
import com.jgoodies.forms.factories.FormFactory;
import com.jgoodies.forms.layout.RowSpec;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;

@SuppressWarnings("serial")
public class TestFrame extends JFrame {

	/**
	 * 
	 */
	private JPanel contentPane;
	private DBHelper db = new DBHelper();
	private String frameTitle = "Snippet Manager Beta 1";

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					TestFrame frame = new TestFrame();
					frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	private final JList<String> listTitle = new JList<String>();
	private JTextArea paneBody = new JTextArea();
	JEditorPane paneTags = new JEditorPane();
	MyListListener myListener = new MyListListener();
	private final JButton btnSave = new JButton("Save");
	private final JButton btnNew = new JButton("New");
	private final JEditorPane paneTitle = new JEditorPane();
	private final JScrollPane scrollPane = new JScrollPane();
	private final JScrollPane scrollPane_1 = new JScrollPane();
	private final JButton btnDeleteAll = new JButton("Delete All");
	private final JButton btnDeleteSelected = new JButton("Delete Selected");
	private final JButton btnSearch = new JButton("Search");
	private final JButton btnReset = new JButton("Reset");
	/**
	 * Create the frame.
	 * @throws SQLException 
	 */
	public TestFrame() throws SQLException {

		this.setTitle(frameTitle);

		setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		setBounds(100, 100, 566, 284);
		contentPane = new JPanel();
		contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
		setContentPane(contentPane);
		contentPane.setLayout(new FormLayout(new ColumnSpec[] {
				ColumnSpec.decode("90px:grow"),
				ColumnSpec.decode("86px"),
				FormFactory.LABEL_COMPONENT_GAP_COLSPEC,
				ColumnSpec.decode("318px:grow"),},
				new RowSpec[] {
				FormFactory.UNRELATED_GAP_ROWSPEC,
				RowSpec.decode("23px"),
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,
				FormFactory.RELATED_GAP_ROWSPEC,
				RowSpec.decode("default:grow"),
				FormFactory.RELATED_GAP_ROWSPEC,
				FormFactory.DEFAULT_ROWSPEC,}));
		contentPane.add(btnNew, "1, 2, left, top");

		contentPane.add(btnSave, "2, 2, left, top");

		paneTitle.setToolTipText("Snippet's Title");
		contentPane.add(paneTitle, "4, 2, fill, center");

		contentPane.add(scrollPane_1, "1, 4, 2, 1, fill, fill");
		scrollPane_1.setViewportView(listTitle);

		fillList();
		listTitle.addListSelectionListener(myListener);

		contentPane.add(scrollPane, "4, 4, fill, fill");
		scrollPane.setViewportView(paneBody);
		paneBody.setToolTipText("Snippt's Body");
		paneBody.setWrapStyleWord(true);
		
		contentPane.add(btnSearch, "1, 10, left, center");
		
		contentPane.add(btnReset, "2, 10, left, center");

		contentPane.add(btnDeleteAll, "1, 14, left, bottom");

		contentPane.add(btnDeleteSelected, "2, 14, left, bottom");
		paneTags.setToolTipText("Snippet's Tags (java, sql, etc.)");
		contentPane.add(paneTags, "4, 14, fill, center");


		BtnResetPressed btnrst = new BtnResetPressed();
		BtnSearchPressed btnsrch = new BtnSearchPressed();
		BtnSavePressed btnpr = new BtnSavePressed();
		BtnSaveNew btnsave = new BtnSaveNew();
		BtnDeleteAllRecords deleteall = new BtnDeleteAllRecords();
		BtnDeleteSelected deleteSelected = new BtnDeleteSelected();
		btnSave.addActionListener(btnpr);
		btnNew.addActionListener(btnsave);
		btnDeleteSelected.addActionListener(deleteSelected);
		btnDeleteAll.addActionListener(deleteall);
		btnSearch.addActionListener(btnsrch);
		btnReset.addActionListener(btnrst);

	}

	private void fillList(){
		try {
			listTitle.setListData(db.getTitles());
		} catch (SQLException e) {
			
			e.printStackTrace();
			errorDialog(e);
		}
	}
	
	private void fillList(String [] listObjects){
		listTitle.setListData(listObjects);
	}
	
	private void errorDialog(Exception e){
		String message = "There has been an error:\n\nStack Trace:\n" + e.toString();
		JOptionPane.showMessageDialog(null, message, "Error!", JOptionPane.ERROR_MESSAGE);
	}
	
	class BtnResetPressed implements ActionListener{

		@Override
		public void actionPerformed(ActionEvent arg0) {
			fillList();
		}
	}
	
	class BtnSearchPressed implements ActionListener{
		public void actionPerformed(ActionEvent arg0) {
			
			String searchTerm = JOptionPane.showInputDialog(null, "Enter your search term");
			try {
				fillList(db.getTitlesFromTagSearch(searchTerm));
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				errorDialog(e);
			}
		}
	}

	class BtnSaveNew implements ActionListener{
		public void actionPerformed(ActionEvent arg0) {

			String title = paneTitle.getText();
			String body = paneBody.getText();
			String tags = paneTags.getText();



			try {
				String [] title_array = db.getTitles();
				boolean match = false;
				for (int i=0; title_array.length > i; i++){
					if (title.contentEquals(title_array[i])){
						JOptionPane.showMessageDialog(null, "Please rename your title.\n You already have an entry with the same name.",
								"Error", JOptionPane.WARNING_MESSAGE);
						match = true;
					}
				}
				if (title.isEmpty()){
					match = true;
					JOptionPane.showMessageDialog(null, "Your title cannot be empty", "Error", JOptionPane.ERROR_MESSAGE);
				}
				if (!match){
					db.newEntry(title, body, tags);
					fillList();
				}
			} catch (SQLException e) {
				errorDialog(e);
				e.printStackTrace();
			}
		}
	}

	class BtnDeleteAllRecords implements ActionListener{
		public void actionPerformed(ActionEvent arg0) {
			
			int confirm = JOptionPane.showConfirmDialog(null, 
					"Are you sure you want to DELETE ALL records?\nTHIS CANNOT BE UNDONE",
					"Confirm Delete All",
					JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION){
				try {
					db.dropDB();
					db.createDB();
					fillList();
				} catch (SQLException e) {
					
					errorDialog(e);
					e.printStackTrace();
				}
			}
		}
	}

	class BtnDeleteSelected implements ActionListener{
		public void actionPerformed(ActionEvent e) {
			
			int confirm = JOptionPane.showConfirmDialog(null, 
					"Are you sure you want to DELETE this record?\nTHIS CANNOT BE UNDONE",
					"Confirm Delete Selected Record",
					JOptionPane.YES_NO_OPTION);
			if (confirm == JOptionPane.YES_OPTION){
				try {
					db.deleteEntry((String)listTitle.getSelectedValue());
					fillList();
				} catch (SQLException e1) {
					
					errorDialog(e1);
					e1.printStackTrace();
				}
			}
		}
	}

	class BtnSavePressed implements ActionListener{

		public void actionPerformed(ActionEvent arg0) {
			String oldtitle = (String)listTitle.getSelectedValue();
			String body = paneBody.getText();
			String tags = paneTags.getText();
			String newtitle = paneTitle.getText();
			try {
				db.updateEntry(oldtitle, newtitle, body, tags);
				fillList();
			} catch (SQLException e) {
				
				e.printStackTrace();
				errorDialog(e);
			}
		}

	}

	class MyListListener implements ListSelectionListener{

		public void valueChanged(ListSelectionEvent e) {
			
			if(e.getValueIsAdjusting()){
				String selectedTitle = (String)listTitle.getSelectedValue();
				setBodyAndTagsFields(selectedTitle);
			}
		}
	}

	public void setBodyAndTagsFields(String s){
		try {
			String [] myBodyAndTags = db.getBodyAndTags(s);
			paneBody.setText(myBodyAndTags[0]);
			paneTags.setText(myBodyAndTags[1]);
			paneTitle.setText(s);
			//myFrame.pack();
		} catch (SQLException e) {
			
			e.printStackTrace();
		}
	}
}

